package org.skf.common.log

import android.content.Context
import android.util.Log
import com.orhanobut.logger.*
import org.skf.common.BuildConfig
import timber.log.Timber
import java.io.File


var logEnable = false
private const val LOG_DIR = "logs"

/**
 * [logEnable] 默认关闭磁盘日志存储，只存储ERROR级别日志
 * [LOG_DIR] 日志存储路径 /sdcard/Android/data/xxx.xxx.xx/caches/LOG_DIR
 * [version] 应用版本信息
 */
fun Context.defaultLogConfig(version: String? = null) {
    if (BuildConfig.DEBUG) {
        val debug = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(true)
            .tag(BuildConfig.owner) // 个人日志标记
            .build()
        Logger.addLogAdapter(AndroidLogAdapter(debug))
        Timber.plant(object : Timber.DebugTree() {
            override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
                Logger.log(priority, tag, message, t)
            }
        })
    } else {
        val file = this.externalCacheDir ?: return
        // 初始化日志存储路径
        logDir = File(file, LOG_DIR).apply { mkdir() }.absolutePath
        SaveLogThread.launch {
            val release = CsvFormatStrategy.newBuilder()
                .tag(version)
                .logStrategy(DiskLogStrategy(SaveLogThread.handler))
                .build()
            Logger.addLogAdapter(DiskLogAdapter(release))
            Timber.plant(object : Timber.Tree() {
                override fun isLoggable(tag: String?, priority: Int): Boolean {
                    return logEnable || priority == Log.ERROR
                }

                override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
                    Logger.log(priority, tag, message, t)
                }
            })
        }
    }
}